/*
 * @Description: 用于touch事件的一些处理
 * @Author: 无痕
 * @Email: 350801869@qq.com
 * @Date: 2021-08-08 18:20:11
 * @LastEditTime: 2021-08-21 14:05:45
 * @LastEditors: 无痕
 */
const MIN_DISTANCE = 10;

function getDirection(x, y) {
  if (x > y && x > MIN_DISTANCE) {
    return 'horizontal';
  }
  if (y > x && y > MIN_DISTANCE) {
    return 'vertical';
  }
  return '';
}

export default function useTouch() {
  return {
    startX: 0,
    startY: 0,
    deltaX: 0,
    deltaY: 0,
    offsetX: 0,
    offsetY: 0,
    direction: '',
    isVertical() {
      return this.direction === 'vertical';
    },
    isHorizontal() {
      return this.direction === 'horizontal';
    },
    getEventAxis(e) {
      return e.touches ? e.touches[0] : e.target;
    },
    reset() {
      this.deltaX = 0;
      this.deltaY = 0;
      this.offsetX = 0;
      this.offsetY = 0;
      this.direction = '';
    },
    start(e) {
      this.reset();
      const touch = e.touches[0];
      this.startX = touch.clientX;
      this.startY = touch.clientY;
    },
    move(e) {
      const touch = e.touches[0];
      this.deltaX = touch.clientX - this.startX;
      this.deltaY = touch.clientY - this.startY;
      this.offsetX = Math.abs(this.deltaX);
      this.offsetY = Math.abs(this.deltaY);
      this.direction = this.direction || getDirection(this.offsetX, this.offsetY);
    },
  };
}
